#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <time.h>
#include <errno.h>
#include <sys/wait.h>
#include "public.h"


int trace_level = MSG_LEVEL_OFF;

void printhelp(void)
{
    printf("Usage:keyled-daemon [options]\n");
    printf("options:\n");
    printf("  -d no debug-level \t\t Increase debug verbosity level\n");
    printf("  -D Num set-debug-level \t Set the debug verbosity level\n");
    printf("      0  minimum\n");
    printf("      1  error\n");
    printf("      2  warning\n");
    printf("      3  info\n");
    printf("      4  verbose\n");
    printf("      5  debug\n");
    printf("      6  maximum\n");
    printf("  -h help \t\t\t Display this information\n");
}

static int progarm_para(int argc, char ** argv)
{
    int c;
    const char * opts;
    int level = -1;

    opts = "dD:h";

    while((c = getopt(argc, argv, opts)) != -1) {
        switch(c) {
        case 'd':
            trace_level = MSG_LEVEL_OFF;
            break;

        case 'D':
            level = atoi(optarg);
            trace_level = level;

            if (level < MSG_LEVEL_OFF)
                trace_level = MSG_LEVEL_OFF;
            else if (level > MSG_LEVEL_MAX)
                trace_level = MSG_LEVEL_MAX;
            ac_traces(MSG_LEVEL_INFO, "trace_level = %d level = %d\n", trace_level, level); 
            break;

        case 'h':
            printhelp();
            exit(1);
            break;
        }
    }

    return true;
}

int main(int argc, char ** argv)
{
    if (argc >= 2) {
        progarm_para(argc, argv);
    }

#if 1
    if (-1 == daemon(1, 1)) {
        pr_err("daemon error, key-daemon exit!\n");
        return false;
    }
#endif

    ac_traces(MSG_LEVEL_INFO, "key daemon created!");

    if (!xy_key_open()) {
        return false;
    }

    xy_key_press_thread_run();
    xy_network_thread_run();

    return true;
}
